function FrontStorage(storageType) {
  this.storage = window[storageType]
}

// 存储基础数据
FrontStorage.prototype.setItem = function (key, value) {
  this.storage.setItem(key, value)
}

// 获取基础数据
FrontStorage.prototype.getItem = function (key) {
  return this.storage.getItem(key)
}

/**
 * 存储 Object 数据
 * @param key
 * @param object
 * @param expired 时效，单位ms
 */
FrontStorage.prototype.setObject = function (key, object, expired) {
  const data = { DATA: object }
  if (expired > 0) {
    data.EXPIRED = Date.now() + expired
  }
  this.setItem(key, JSON.stringify(data))
}

/**
 * 获取 object 数据
 * @param key
 * @returns {object}
 */
FrontStorage.prototype.getObject = function (key) {
  try {
    const data = JSON.parse(this.getItem(key))
    if (data) {
      if (data.EXPIRED && data.EXPIRED <= Date.now()) {
        this.removeItem(key)
        return null
      }
      return data.DATA
    }
  } catch (e) {
    return null
  }
}

// 获取 boolean 数据
FrontStorage.prototype.getBoolean = function (key) {
  const string = this.getItem(key)
  return !(
    !string ||
    string === 'undefined' ||
    string === 'null' ||
    string === 'false' ||
    string === '0'
  )
}

// 获得 number 数据
FrontStorage.prototype.getNumber = function (key) {
  const string = this.getItem(key)
  return Number(string)
}

// 根据 key 删除数据
FrontStorage.prototype.removeItem = function (key) {
  this.storage.removeItem(key)
}

// 清空数据
FrontStorage.prototype.clear = function () {
  this.storage.clear()
}

export const local = new FrontStorage('localStorage')
export const session = new FrontStorage('sessionStorage')
export default {
  local: local,
  session: session
}
